import Icon from '@/components/Icon';
import Input from '@/components/Input';
import NavBar from '@/components/NavBar';
import { baseURL } from '@/utils/requset';
import { getToken } from '@/utils/storage';
import { Toast } from 'antd-mobile';
import classNames from 'classnames';
import { useEffect, useRef, useState } from 'react';
import { io, Socket } from 'socket.io-client';
import styles from './index.module.scss';

/*
  学习目标：小智同学-聊天信息非空，支持回车发送消息
*/

type MsgType = {
  msg: string;
  type: string;
  timestamp: number;
};
export default function Chat() {
  const sokRef = useRef<Socket | null>(null);
  const [msgList, setMsgList] = useState<MsgType[]>([]);
  useEffect(() => {
    sokRef.current = io(baseURL, {
      query: {
        token: getToken(),
      },
      transports: ['websocket'],
    });

    sokRef.current.on('connect', () => {
      setMsgList([{ msg: '欢迎来到黑马, 你有什么问题吗？', type: 'robot', timestamp: Date.now() }]);
    });

    sokRef.current.on('message', (data) => {
      setMsgList((preMsgList) => {
        return [...preMsgList, { ...data, type: 'robot' }];
      });
    });
    return () => {
      sokRef.current?.close();
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect(() => {
    window.scrollTo({
      top: document.body.scrollHeight,
      behavior: 'smooth',
    });
  }, [msgList]);

  const [msg, setMsg] = useState('');
  const handleSubmit = () => {
    if (!msg.trim()) {
      Toast.show({ content: '不能发送空消息' });
      return;
    }
    sokRef.current?.emit('message', { msg, timestamp: Date.now() });
    setMsgList([...msgList, { msg, timestamp: Date.now(), type: 'user' }]);

    setMsg('');
  };

  function handleKeyDown(e: React.KeyboardEvent<HTMLInputElement>): void {
    if (e.key === 'Enter') {
      handleSubmit();
    }
  }

  return (
    <div className={styles.root}>
      <NavBar fixed>小智同学</NavBar>

      <div className="chat-list">
        {msgList.map((item) => {
          return (
            <div
              key={item.timestamp}
              className={classNames('chat-item', { user: item.type === 'user' })}
            >
              {item.type === 'robot' ? (
                <Icon type="iconbtn_xiaozhitongxue" />
              ) : (
                <img src={'http://toutiao.itheima.net/images/user_head.jpg'} alt="" />
              )}

              <div className="message">{item.msg}</div>
            </div>
          );
        })}
      </div>

      <div className="footer">
        {/* 底部消息输入框 */}
        <div className="input-footer">
          <Input
            className="no-border"
            placeholder="请描述您的问题"
            value={msg}
            onChange={(e) => setMsg(e.target.value)}
            onKeyDown={(e) => handleKeyDown(e)}
          />
          <Icon type="iconbianji" />
          <span className="send" onClick={handleSubmit}>
            发送
          </span>
        </div>
      </div>
    </div>
  );
}
